package com.tarena.lbs.attach.dao.repository.impl;

import com.tarena.lbs.attach.dao.mapper.AttachMapper;
import com.tarena.lbs.attach.dao.repository.AttachRepository;
import com.tarena.lbs.attach.pojo.po.AttachPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Slf4j
@Repository
public class AttachRepositoryImpl implements AttachRepository {
    @Autowired
    private AttachMapper attachMapper;
    @Override
    public Integer add(String fileName, String fileUrl) {
        AttachPO attachPO = new AttachPO();
        attachPO.setFileUuid(fileName);
        attachPO.setClientFileName(fileUrl);
        attachMapper.insert(attachPO);
        return attachPO.getId();
    }

    @Override
    public String getAttachUrl(String id) {
        // 添加空值检查
        if (id == null || id.trim().isEmpty()) {
            log.warn("图片ID为空");
            return null;
        }
        
        try {
            Integer idInt = Integer.parseInt(id.trim());
            AttachPO attachPO = attachMapper.selectById(idInt);
            // 添加空值检查
            if (attachPO == null) {
                log.warn("未找到ID为{}的图片记录", idInt);
                return null;
            }
            return attachPO.getClientFileName();
        } catch (NumberFormatException e) {
            log.error("图片ID格式错误: {}", id, e);
            return null;
        } catch (Exception e) {
            log.error("获取图片URL失败，图片ID: {}", id, e);
            return null;
        }
    }
}